package com.yeban.javase.day16.created;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/29
 */
public class CallableDemo {

    public static void main(String[] args) {
        // 创建任务
        // 创建Callable对象
        MyCallable task1 = new MyCallable();

        // 使用匿名内部类创建 Callable（带返回值）
        Callable<Integer> task2 = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 10; i++) {
                    System.out.println(Thread.currentThread().getName() + " --- " + i);
                    sum += i;
                }
                return sum;
            }
        };

        // 使用Lambda表达式
        Callable<Integer> task3 = () -> {
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + " --- Lambda --- " + i);
                sum += i;
            }
            return sum;
        };

        // 调用FutureTask包装Callable
        FutureTask<Integer> ft1 = new FutureTask<>(task1);
        FutureTask<Integer> ft2 = new FutureTask<>(task2);
        FutureTask<Integer> ft3 = new FutureTask<>(task3);

        // 用Thread执行任务，Thread构造函数可以传入FutureTask类型
        Thread thread1 = new Thread(ft1);
        Thread thread2 = new Thread(ft2);
        Thread thread3 = new Thread(ft3);

        new Thread(ft1, "线程-1").start();
        new Thread(ft2, "线程-2").start();
        new Thread(ft3, "线程-3").start();



        // 接收返回值
        try {
            // 通过FutureTask中的get方法获取线程返回的结果
            Integer result1 = ft1.get();
            Integer result2 = ft2.get();
            Integer result3 = ft3.get();
            System.out.println("线程返回结果：" + result1);
            System.out.println("线程返回结果：" + result2);
            System.out.println("线程返回结果：" + result3);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

class MyCallable implements Callable {
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 10; i++) {
            System.out.println(Thread.currentThread().getName() + " --- " + i);
            sum += i;
        }
        return sum;
    }
}
